package ${model_package_serviceImpl};

import com.modules.utils.BeanUtils;
import com.modules.utils.MessageConstant;
import com.wxp.dao.${model_name}Dao;
import com.wxp.entity.${model_name};
import com.wxp.service.${model_name}Service;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* Created by lewis on ${.now}.
*/
@Service
@Transactional
public class ${model_name}ServiceImpl implements ${model_name}Service {
    private static Logger logger	= LoggerFactory.getLogger(${model_name}ServiceImpl.class);

    @Autowired
    private ${model_name}Dao ${model_name_entity}Dao;

    @Override
    public Page<${model_name}> findAll(Specification spec, PageRequest pageRequest) {
        return ${model_name_entity}Dao.findAll(spec,pageRequest);
    }

    @Override
    public ${model_name} findBy${model_key_by}(String ${model_key}) {
        return ${model_name_entity}Dao.findBy${model_key_by}(${model_key});
    }
    @Override
    public String save${model_name}(${model_name} ${model_name_entity}) {
        String primaryKey = ${model_name_entity}.get${model_key_by}();
        String result = null;
        ${model_name} existed = null;
        if (StringUtils.isNotEmpty(primaryKey)) {
            existed = ${model_name_entity}Dao.findBy${model_key_by}(primaryKey);
        }
        if (existed == null) {//新增
            ${model_name_entity}Dao.save(${model_name_entity});
        }else {//修改，需要将表单上修改后的指定属性复制到从数据库中取回来的已有对象上
            //判断是否可以保存，如果页面上的version值和数据库中的version值不一致，则说明在编辑这条记录的过程中，别人已经编辑并更新过了
            if ((existed.getVersion() != null) && (existed.getVersion().intValue() != ${model_name_entity}.getVersion().intValue())){
                result = MessageConstant.OUT_OF_DATE;//已经被别人编辑更新过了
            } else {
                String[] properties = new String[]{${model_properties}};
                BeanUtils.copyAssignProperties(${model_name_entity}, existed, properties);
                this.${model_name_entity}Dao.save(existed);
            }
        }
        return result;
    }

}
